<?php
/**
 * Created by PhpStorm.
 * User: gyccvvh
 * Date: 2018-06-15
 * Time: 16:56
 */

namespace app\home\controller;


use think\Db;

class Mermenu extends Basic
{
    public function _initialize()
    {
        parent::_initialize();
        $arr[0]['text']   = '菜单列表';
        $arr[0]['url']    = 'index';
        $arr[1]['text']   = '新增菜单';
        $arr[1]['url']    = 'add';
        $this->assign('third_menu', $arr);
    }
    public function index() {
        $list = Db::table("sp_mer_menu")->where("type","in","(0,3,2)")->order('listorder ASC')->select();
        $tree = new \thans\Common\tree($list);
        $list = $tree->formatArrayForTree("id","pid","name");

        $menu_pids = array();
        foreach($list as $value) {
            $menu_pids[] = $value['pid'];
        }

        $levelArray = array();
        foreach($list as $value) {
            if(isset($levelArray[$value['pid']])) {
                $levelArray[$value['id']] = $levelArray[$value['pid']] + 1;
            }else {
                $levelArray[$value['id']] = 0;
            }
        }

        foreach ($list as $key => $value) {
            //根据对应的层级显示  模块\控制器\方法
            if (isset($levelArray[$value['id']])) {
                if ($levelArray[$value['id']] == 1) {
                    $list[$key]['model'] = $value['controller'];
                } else if ($levelArray[$value['id']] == 2) {
                    $list[$key]['model'] = $value['action'];
                }
                $list[$key]['model'] = $value['model'] . '/' . $value['controller'] . '/' . $value['action'];
            }
            $list[$key]['action'] = '<a href="' . url('edit', 'id=' . $list[$key]['id']) . '"><i class="layui-icon layui-icon-edit"></i></a>&nbsp;<i class="layui-icon layui-icon-delete" action-url="' . url('del', 'id=' . $list[$key]['id']) . '" data-info="您确定要删除本菜单吗？" action="del" title="删除"></i>';
            $list[$key]['status'] = $value['status'] ? "显示" : "隐藏";
        }
        $tree->initArr($list);
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $str        = "<tr><td style='width:64px;'><input type='hidden' name='id[]' value='\$id'><input type='text' name='order[]'  class = 'form-control' style='width:60px;' value='\$listorder' class='pxinput'></td>
        <td>\$id</td>
        <td>\$spacer\$name</td>
        <td>\$model</td>
        <td>\$status</td>
        <td>\$level</td>
        <td>\$action</td></tr>";
        $list = $tree->get_tree(0, $str);
        $this->assign('list', $list);
        return $this->fetch('index');
    }

    public function getOptionTree($select = 0) {
        $list = Db::table("sp_mer_menu")->select();
        $tree = new \thans\Common\tree($list);
        $tree->formatArrayForTree('id', 'pid', 'name');
        $data = $tree->get_tree(0, "<option value='\$id' \$selected>\$spacer \$name </option>", $select);
        return $data;
    }
    public function add() {
        if($this->request->isPost()) {
            $model      = trim(strtolower(input('model')));
            $controller = trim(strtolower(input('controller')));
            $action     = trim(strtolower(input('action')));
            $data       = trim((string) input('data'));
            $status     = input('status');
            $status     = $status ? 1 : 0;
            $type       = intval(input('type'));
            $rule_value = "{$model}/{$controller}/{$action}";
            $level = input('level', 1);

            $data = array(
                'pid'   => intval(input('pid')),
                'name'       => trim((string) input('name')),
                'model'      => $model,
                'controller' => $controller,
                'action'     => $action,
                'data'       => $data,
                'icon'       => trim((string) input('icon')),
                'remark'     => trim((string) input('remark')),
                'rule_value' => $rule_value,
                'listorder'  => intval(input('listorder')),
                'type'       => $type,
                'option'    => trim((string) input('option')),
                'status'     => $status,
                'level'     => $level,
            );
            Db::startTrans();
            try{
                $menu_id = Db::table("sp_mer_menu")->insertGetId($data);
                if(!$menu_id) {
                    return $this->ret->setCode(1)->setMsg("添加失败")->toJson();
                }
                if(!$type) {
                    Db::commit();
                    return $this->ret->setMsg("添加成功")->setReload()->toJson();
                }
                Db::commit();
                return $this->ret->setMsg('添加成功')->setData('menu_id', $menu_id)->setReload()->toJson();
            }catch (\Exception $e) {
                Db::rollback();
                return $this->ret->setCode(2)->setMsg("添加失败")->toJson();
            }
        }else {
            $this->assign("menulist",$this->getOptionTree(0));
            return $this->fetch();
        }
    }

    public function del(){
        $id = input("id");
        $res = Db::table("sp_mer_menu")->where("id",$id)->delete();
        if($res) {
            return $this->ret->setCode(0)->setMsg("删除成功")->toJson();
        }else {
            return $this->ret->setCode(1)->setMsg("删除失败")->toJson();
        }
    }
    public function listorder()
    {
        $ids = input('id/a');
        $orders = input('order/a');
        foreach($ids as $key => $v){
            $res = Db::table("sp_mer_menu")->update(["id"=>$v,"listorder" => $orders[$key]]);
        }
        if ($res) {
            return $this->ret->setCode(0)->setMsg('排序更新成功')->setReload()->toJson();
        } else {
            return $this->ret->setCode(1)->setMsg('排序更新失败')->toJson();
        }
    }
    public function edit(){
        if($this->request->isPost()) {
            $model      = trim(strtolower(input('model')));
            $controller = trim(strtolower(input('controller')));
            $action     = trim(strtolower(input('action')));
            $data       = trim((string) input('data'));
            $status     = input('status');
            $status     = $status ? 1 : 0;
            $type       = intval(input('type'));
            $rule_value = "{$model}/{$controller}/{$action}";
            $level = input('level', 1);
            $data = array(
                'pid'   => intval(input('pid')),
                'name'       => trim((string) input('name')),
                'model'      => $model,
                'controller' => $controller,
                'action'     => $action,
                'data'       => $data,
                'icon'       => trim((string) input('icon')),
                'remark'     => trim((string) input('remark')),
                'option'    => trim((string) input('option')),
                'rule_value' => $rule_value,
                'type'       => $type,
                'status'     => $status,
                'level'     => $level,
            );
            if (input('listorder') != '') {
                $data['listorder'] = intval(input('listorder'));
            }
            Db::startTrans();
            try {
                $res = Db::table("sp_mer_menu")->where($data)->find();
                if ($res) {
                    return $this->ret->setCode(0)->setMsg('更新成功')->toJson();
                }
                $menu_status = Db::table("sp_mer_menu")->where('id', input('id'))->update($data);
                if (!$menu_status) {
                    return $this->ret->setCode(1)->setMsg('更新失败')->toJson();
                }
                Db::commit();
                return $this->ret->setMsg('更新成功')->setReload()->toJson();

            } catch (\Exception $e) {
                throw $e;
                Db::rollback();
                return $this->ret->setCode(1)->setMsg('更新失败')->toJson();
            }
        }else {
            $id = input('id');
            $list = Db::table("sp_mer_menu")->where("id",$id)->find();
            $this->assign("data",$list);
            $selectid = $list['pid'];
            $this->assign("menulist",$this->getOptionTree($selectid));
            return $this->fetch();
        }
    }
}